<template>
  <div
    class="app-content">
    <div class="vip_wrap">
      <div
        class="vip_box"
        :class="[roleType==1?'personalVip':'enterprise',{on: sel}]"
        @click="sel = !sel">
        <div class="price">
          <span class="symbol">￥</span>
          <span class="num">{{ roleType==1?personal.price: company.price }}</span>
          <span class="unit">/年</span>
        </div>
        <div class="vip_period">
          {{ isVip == 'true'?roleType==1?personal.end_time+'到期': company.end_time+'到期': '' }}
        </div>
        <div class="sel"/>
      </div>
    </div>
    <div class="year_num">
      <div class="left">购买年限/年</div>
      <div class="right">
          <uni-number-box :value="year" :min="1" @change="updateYear"></uni-number-box>
        <!-- <van-stepper
          v-model="year"
          integer
          input-width="50px"
          button-size="29px"
          @change="getPayInfo"
        /> -->
      </div>
    </div>

    <p class="validity_period">购买后有效期至{{ period }}</p>
    <div
      class="account_price"
      v-if="roleType == 0 && isVip == 'true'">
      <div class="left">已购买子账号 {{ hasAccount }}</div>
      <div class="right">
        <!-- <span class="past_price">(原价{{ account.has_account_original_price | toFix }})&nbsp;&nbsp;</span> -->
        <span class="now_price">¥{{ account.has_account_price | toFix }}</span>
      </div>
    </div>
    <div class="vip_price">
      <div class="left">支付金额</div>
      <div class="right">
        <!-- <span class="past_price">(原价{{ this.originPrice | toFix }})&nbsp;&nbsp;</span> -->
        <span class="now_price">¥{{ total | toFix }}</span>
      </div>
    </div>

    <div v-if="roleType==0">
      <div class="add_service">
        <div
          class="left_sel"
          :class="{on: addSubAccount}"
          @click="addSubAccount = !addSubAccount"/>
        <h2>增值服务<span>（子账号不够点击添加）</span></h2>
      </div>
      <div
        class="add_subAccount"
        v-show="addSubAccount">
        <p class="top">
          <span class="left">增加子账号</span>
          <span class="right">{{ account.account_price | toFix }}元</span>
        </p>
        <div class="bottom">
          <div class="left">
            <p class="subAccount_validity_period">有效期至：{{ period }}</p>
            <p class="unit_price"><span class="now">￥{{ sub_account.price | toFix }}/个</span>
              <!-- <span class="past">（原价{{ sub_account.original_price | toFix }}元）</span> -->
            </p>
          </div>
          <div class="right">
              <uni-number-box :value="subAccountNum" :min="0" @change="updateNum"></uni-number-box>
          </div>
        </div>

      </div>
    </div>

    <div
      class="purchase_tips"
      v-if="roleType==0">
      <p>温馨提示：</p>
      <p>1.企业版：默认包含11个账号，其中一个为管理账号
      （即当前登入账号），您还可以增加10个子账号。</p>
      <p>2.增值服务：购买增加子账号个数</p>
    </div>
    <!-- :class="[roleType == 1 ? '' : 'fixed']" -->
    <div
      class="pay_btn"
      @click="pay"
    >确认支付
      <!-- <span>（节省¥{{ saveNum | toFix }}）</span> -->
    </div>
  </div>
</template>

<script>
import qs from 'qs'
// import { Promise, reject } from 'q';
// import { resolve } from 'url';
import { getVIPInfo, getPayInfo } from '@/api/vip'
import { payVIP } from '@/api/payment'
import uniNumberBox from '@/components/uni-number-box'
import { setTimeout } from 'timers'

const moment = require('moment')

export default {
	name: 'PurchaseVip',
	components: {
		uniNumberBox
	},
	data() {
		return {
			addSubAccount: false,
			sel: true,
			subAccountNum: 0,
			year: 1,
			roleType: '',
			personal: {},
			company: {},
			sub_account: {},
			isVip: 'false',
			total: '',
			saveNum: '',
			originPrice: '',
			hasAccount: 0,
			account: {},
			loading: false
		}
	},
	onLoad(option) {
		const { roleType, isVip } = option
		this.roleType = roleType
		this.isVip = isVip
	},
	onShow() {
		this.init()
	},
	filters: {
		toFix(val) {
			return Number(val).toFixed(2)
		}
	},
	watch: {
		addSubAccount() {
			if (this.subAccountNum && !this.loading) {
			    this.getPayInfo()
			}
		},
		loading(val) {
			if (val) {
				uni.showLoading({
					title: '',
					mask: true
				})
			} else {
				uni.hideLoading()
			}
		}
	},
	computed: {
		period() {
			if (this.isVip == 'true') {
				const end_time = this.roleType == 1 ? this.personal.end_time : this.company.end_time
				return moment(end_time).add(this.year, 'years').format('YYYY-MM-DD')
			}
			return moment().add(this.year, 'years').format('YYYY-MM-DD')
		}
	},
	methods: {
		init() {
			getVIPInfo().then((res) => {
				this.company = res.data.company || {}
				this.sub_account = res.data.sub_account || {}
				this.personal = res.data.personal || {}
			})
			this.getPayInfo()
		},
		updateYear(val) {
			this.year = val
			!this.loading && this.getPayInfo()
		},
		updateNum(val) {
			this.subAccountNum = val
			!this.loading && this.getPayInfo()
		},
		getPayInfo() {
			this.loading = true
			const params = {
				type: this.roleType == 1 ? 'personal' : 'company',
				counter: this.year
			}
			if (this.roleType == 0 && this.addSubAccount) {
				params.sub_account_num = this.subAccountNum
			}
			getPayInfo(params).then((res) => {
				this.loading = false
				const { price, save_price } = res.data
				this.total = price
				this.saveNum = save_price
				this.originPrice = parseFloat(price) + parseFloat(save_price)
				if (this.roleType == 0) {
					const { account, has_account } = res.data
					this.account = account
					this.hasAccount = has_account
				}
			})
		},
		pay() {
			if (this.roleType == 1) {
				if (!this.sel) {
					uni.showToast({
						title: '请选择购买的服务',
						icon: 'none'
					})
					return
				}
			} else {
				if (!this.sel && !this.addSubAccount) {
                    	uni.showToast({
						title: '请选择购买的服务',
						icon: 'none'
					})
					return
				}
				if (!this.sel && this.isVip == 'false') {
                       	uni.showToast({
						title: '请选择vip',
						icon: 'none'
					})
					return
				}
			}
			const params = {
				type: this.roleType == 1 ? 'personal' : 'company',
				counter: this.sel ? this.year : 0
			}
			if (this.roleType == 0 && this.addSubAccount) {
				params.sub_account_num = this.subAccountNum
			}

			// #ifdef H5
			payVIP(params).then((res) => {
				if (res.data.pay_button.paycode == 'wxpay') {
					if (res.data.pay_button.type == 'wxh5') {
						window.location.href = `${res.data.pay_button.mweb_url}?redirect_url=${encodeURIComponent(this.$route.query.url)}`
					} else {
						this.callpay(res.data.pay_button)
					}
				} else {
					// this.submit_btn = res.data.pay_button
				}
			})
			// #endif

			// #ifdef MP-WEIXIN
			const tranParams = qs.stringify({
				from: 'vip',
				requestParams: JSON.stringify(params)
			})
			uni.navigateTo({
				url: `/pages/page/payMent/main?${tranParams}`
			})
			// #endif
		},
		callpay(ret) {
			if (typeof WeixinJSBridge === 'undefined') {
				if (document.addEventListener) {
					document.addEventListener('WeixinJSBridgeReady', this.jsApiCall(ret), false)
				} else if (document.attachEvent) {
					document.attachEvent('WeixinJSBridgeReady', this.jsApiCall(ret))
					document.attachEvent('onWeixinJSBridgeReady', this.jsApiCall(ret))
				}
			} else {
				this.jsApiCall(ret)
			}
		},
		jsApiCall(ret) {
			const that = this
			const payment = JSON.parse(ret.payment)
			const success_url = ret.success_url
			const cancel_url = ret.cancel_url
			WeixinJSBridge.invoke('getBrandWCPayRequest', payment, (res) => {
				if (res.err_msg == 'get_brand_wcpay_request:ok') {
					uni.showToast({
						title: '支付成功',
						icon: 'none'
					})
					setTimeout(() => {
						uni.redirectTo({
							url: `/pages/admin/vip/vipGuide`
						})
					}, 500)

					// window.location.href = success_url
					/* that.$router.push({
                      name: 'PersonRecharge',
                      query: {
                          owner_user_id: that.$route.query.owner_user_id
                      }
                  }) */
				} else if (res.err_msg == 'get_brand_wcpay_request:fail') {
					uni.showToast({
						title: '支付失败',
						icon: 'none'
					})
				}
			})
		}

	}
}
</script>

<style scoped lang="scss">
@import "~@/uni.scss";
    .app-content {
        position: relative;
        padding-bottom: 100px;
    }
    .add_service {
      display: flex;
      align-items: center;
      padding: 20px 30px 30px;
      h2 {
        span {
          font-size: 24px;
          color: #999;
        }
      }
    }
    .vip_wrap {
        padding: 29px 40px 0;
        background-color: #fff;
    }

    .vip_box {
        position: relative;
        height: 370px;
        background-size: 100% 100%;
        background-repeat: no-repeat;
        &.on {
            .sel {
                background-image: url($imgUrl + 'vip/sel.png');
            }
        }
        .sel {
            position: absolute;
            top: 0;
            right: 0;
            width: 76px;
            height: 76px;
            background-repeat: no-repeat;
            background-size: cover;
            background-image: url($imgUrl + 'vip/unSel.png');
        }
        .price {
            display: flex;
            align-items: center;
            position: absolute;
            left: 30px;
            bottom: 74px;
            color: #252525;
            span {
                margin: 0 !important;
            }
            .symbol {
                font-size: 30px;
            }
            .num {
                font-size: 40px;
            }
            .unit {
                font-size: 24px;
            }
        }
        &.enterprise {
            background-image: url($imgUrl + "vip/company-un-vip.png");
        }
        &.personalVip {
            background-image: url($imgUrl + "vip/person-un-vip.png");
        }
    }

    .vip_price, .account_price {
        padding: 0 30px;
        height: 100px;
        background-color: #fff;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-top: 1px solid rgba(238, 238, 238, 1);
        .left {
            font-size: 28px;
            color: rgba(51, 51, 51, 1);
        }
        .right {
            display: flex;
            align-items: center;
        }
        .past_price {
            font-size: 28px;
            color: #999;
        }
        .now_price {
            font-size: 32px;
            color: #FF6900;
        }
    }

    .vip_period {
        position: absolute;
        right: 42px;
        bottom: 93px;
        font-size: 24px;
        color: rgba(37, 37, 37, 1);
    }

    .year_num {
        padding: 55px 30px 0;
        background-color: #fff;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .left {
            font-size: 28px;
            color: rgba(51, 51, 51, 1);
        }
    }

    .purchase_tips {
        padding: 22px 30px 0;
        p {
            line-height: 36px;
            font-size: 24px;
            color: #999;
        }
    }

    .pay_btn {
        margin: 60px auto 0;
        text-align: center;
        width: calc(100% - 60px);
        height: 90px;
        line-height: 90px;
        background: rgba(255, 209, 26, 1);
        border-radius: 45px;
        font-size: 32px;
        font-weight: bold;
        color: #3A1B04;
        &.fixed {
            margin-top: 0;
            position: fixed;
            bottom: 8px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 999;
        }
        span {
            font-weight: normal;
        }
    }

    .validity_period {
        background-color: #fff;
        text-align: right;
        padding: 20px 30px;
        font-size: 24px;
        color: rgba(153, 153, 153, 1);
    }

    h2 {
      padding-left: 10px;
        font-size: 28px;
        font-weight: 400;
        color: rgba(102, 102, 102, 1);
    }

    .opening_type {
        padding: 30px;
        background-color: #fff;
        .opening_type_item {
            padding: 32px 29px 24px;
            border: 1px solid rgba(221, 221, 221, 1);
            border-radius: 20px;
            & + .opening_type_item {
                margin-top: 20px;
            }
            &.on {
                background: rgba(255, 249, 245, 1);
                border: 2px solid #FF6F0B;
                box-shadow: 0px 8px 16px 0px rgba(115, 115, 115, 0.1);
            }
            .top {
                display: flex;
                justify-content: space-between;
                align-items: center;
                .left {
                    padding-left: 57px;
                    font-size: 36px;
                    color: #333;
                    span {
                        font-size: 24px;
                    }
                    &.personal_icon {
                        background: url($imgUrl + 'vip/personal.png') no-repeat left center/50px 50px;
                    }
                    &.enterprise_icon {
                        background: url($imgUrl + 'vip/enterprise.png') no-repeat left center/50px 50px;
                    }
                }
                .right {
                    font-size: 32px;
                    font-weight: 600;
                    color: rgba(255, 105, 0, 1);
                }
            }
            .past_price {
                font-size: 24px;
                text-decoration: line-through;
                color: rgba(153, 153, 153, 1);
                margin-top: 13px;
                text-align: right;
            }
            .account_num {
                font-size: 28px;
                color: #333;
            }
            .add_feature {
                font-size: 24px;
                color: #333;
                margin-top: 22px;
            }
            .applicable_role {
                font-size: 24px;
                color: #999;
                margin-top: 22px;
            }
        }
    }

    .add_subAccount {
        background-color: #fff;
        position: relative;
        padding: 29px 30px 33px 30px;
        .top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            .left {
                font-size: 30px;
                color: #333;
                span {
                    font-size: 24px;
                }
            }
            .right {
                font-size: 32px;
                font-weight: 600;
                color: rgba(255, 105, 0, 1);
            }
        }
        .bottom {
            margin-top: 20px;
            display: flex;
            justify-content: space-between;
            .left {
                font-size: 24px;
                .subAccount_validity_period {
                    color: #999;
                }
                .unit_price {
                    margin-top: 14px;
                    .now {
                        color: #FF6900
                    }
                    .past {
                        color: #999;
                    }
                }

            }
        }

    }
   .left_sel {
            width: 46px;
            height: 46px;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            border: 1px solid #ccc;
            background-color: #fff;
            &.on {
              border-color: #ffd11a;
                background: url($imgUrl + "common/selected.png") no-repeat center/cover #ffd11a;
            }
      }
    .bottom_bar {
        display: flex;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        width: 100%;
        height: 100px;
        background: rgba(255, 255, 255, 1);
        box-shadow: 0px -3px 10px 0px rgba(0, 0, 0, 0.1);
        .left {
            flex: 1;
            padding: 18px 0 17px 30px;
            height: 100%;
            .total {
                .txt {
                    font-size: 30px;
                    color: #333;
                }
                .num {
                    font-size: 32px;
                    color: #FF6900;
                }
            }
            .account_num {
                font-size: 24px;
                color: rgba(153, 153, 153, 1);
                margin-top: 13px;
            }
        }
        .right {
            width: 250px;
            height: 100%;
            line-height: 100px;
            text-align: center;
            background-color: #FFD11A;
            font-size: 32px;
            color: rgba(58, 27, 4, 1);
        }
    }
</style>
